<template>
  <m-window-frame
    :title="$t('导入')"
    style="height: 100%"
    :okLoading="saveLoading"
    :ok-text="$t('导入')"
    :cancel-text="$t('关 闭')"
    class="v-FHJS-import"
    @cancel="handleCancel"
    @ok="handleSave"
  >
    <div class="FHJS-import-container">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="form"
        label-width="85px"
        :hide-required-asterisk="true"
      >
        <el-form-item
          v-if="solutionCode"
          label="解决方案编码"
        >
          <el-row :gutter="12">
            <el-col :span="24">
              <el-input
                :model-value="solutionCode"
                :disabled="true"
              ></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          :label="$t('包')"
          prop="owner"
        >
          <el-row :gutter="12">
            <el-col :span="24">
              <div class="g-ai-c g-flex-auto ownerBox g-one-line">
                <img
                  v-if="form.owner.icon"
                  :src="form.owner.icon"
                  width="16"
                  height="16"
                  style="margin-right: 4px"
                  onerror="this.src='statics/images/sysml/Stereotype.svg'"
                  alt=""
                />
                <span class="text g-one-line">{{ form.owner.label }}</span>
                <img
                  src="statics/icons/app/iconmore.png"
                  class="_btn"
                  @click="selectOwner"
                />
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          v-if="solutionCode"
          :label="$t('导入地址')"
        >
          <el-row :gutter="12">
            <el-col
              :span="24"
              class="interface-path-box"
            >
              <el-select
                v-model="filePaths"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="4"
                placeholder="请选择"
                style="width: 100%"
                :suffix-icon="SelectSuffix"
              >
                <el-option
                  v-for="item in fileList"
                  :key="item.fileUrl"
                  :label="item.name"
                  :value="item.fileUrl"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    class="glay-text"
                    style="float: right"
                  >
                    {{ item.createTime }}
                  </span>
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- <el-form-item v-if="solutionCode" :label="$t('导入地址')">
          <el-row :gutter="12">
            <el-col :span="24" class="interface-path-box">
              <div class="dropdown-file-box">
                <MDropdown class="g-inline-block" :max-height="80">
                  <div class="g-jc-sb g-pointer dropdown-file-content-box">
                    <div class="g-flex-1 g-one-line dropdown-file-content">
                      <span class="g-pd-lr-7">{{ selectedFile?.name }}</span>
                      <span class="gray-text">{{ selectedFile?.createTime }}</span>
                    </div>
                    <div class="g-flex-0 g-pd-lr-7">
                      <img src = 'statics/icons/app/iconlist2.png'>
                    </div>
                  </div>
                  <template #dropdown>
                    <MDropdownMenuItem v-for="file in fileList" :key="file.fileUrl" @click="selectFile(file)">
                      <span class="g-pd-lr-8">{{ file.name }}</span>
                      <span style="color: gray;">{{ file.createTime }}</span>
                    </MDropdownMenuItem>
                  </template>
                </MDropdown>
              </div>
            </el-col>
          </el-row>
        </el-form-item> -->
        <el-form-item
          v-else
          :label="$t('导入地址')"
          prop="importPath"
        >
          <el-row :gutter="12">
            <el-col
              :span="24"
              class="interface-path-box"
            >
              <el-input v-model="form.importPath"></el-input>
              <div class="dropdown-box">
                <MDropdown class="g-inline-block">
                  <div>
                    <img
                      src="statics/icons/app/iconadd.png"
                      class="g-pointer"
                    />
                  </div>
                  <template #dropdown>
                    <MDropdownMenuItem @click="changePath('dir')">
                      <span class="g-pd-lr-8">{{ $t("选择文件夹") }}</span>
                    </MDropdownMenuItem>
                    <MDropdownMenuItem @click="changePath('zip')">
                      <span class="g-pd-lr-8">{{ $t("选择压缩包") }}</span>
                    </MDropdownMenuItem>
                  </template>
                </MDropdown>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- <el-form-item v-for="item in interfaceTypes" :key="item.value" :label="$t(item.label + '接口路径')" :prop="item.value">
          <el-row :gutter="12">
            <el-col :span="24" class="interface-path-box">
              <el-input v-model="form[item.value]"></el-input>
              <img  src="statics/icons/app/iconmore.png" class="_btn" @click="changePath(item.value)"/>
            </el-col>
          </el-row>
        </el-form-item> -->
        <!-- <el-form-item :label="$t('接口类型')">
          <el-row :gutter="12">
            <el-col :span="24">
              <el-select v-model="form.interfaceType" :suffix-icon="SelectSuffix">
                <el-option v-for="item in interfaceTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item> -->
      </el-form>
    </div>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import { ref, watch, reactive, onBeforeMount } from "vue";
import { Params, CloseData } from "./index";
import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import { locale } from "@/mdesign-lib/mdesign-app.umd.js";
import { modelTreeSelectWindow } from "@/mdesign-lib/mdesign-app.umd.js";
import { PropertyDataType } from "@/mdesign-lib/mdesign-app.umd.js";
import { modelService } from "@/mdesign-lib/mdesign-app.umd.js";
import { MetaclassType } from "@/mdesign-lib/mdesign-app.umd.js";
import { localFile } from "@/mdesign-lib/mdesign-app.umd.js";
import { IpcMsg } from "@/mdesign-lib/mdesign-main.js";
import { ipcRenderer } from "electron";
import MDropdown from "@/mdesign-lib/mdesign-app.umd.js";
import MDropdownMenuItem from "@/mdesign-lib/mdesign-app.umd.js";
import { archService } from "@/mdesign-lib/mdesign-app.umd.js";
import SelectSuffix from "@/modules/model/comps/common/SelectSuffix.vue";
import { sleep } from "@/util/common";
import { archUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import LoadingVue from "@/common/Loading.vue";

interface OptionItem {
  label: string;
  value: string;
  icon?: string;
}

interface FileOption {
  name: string;
  fileUrl: string;
  createTime: string;
}

const form = reactive<Record<string, any>>({
  owner: {
    value: "",
    label: "",
    icon: ""
  },
  importPath: ""
});
// const interfaceTypes = ref<OptionItem[]>([
//   { label: '作战场景集', value: '11Zzcjj' },
//   { label: '体系使命任务', value: '12Txsmrw' },
//   { label: '兵力构成', value: '13Blgc' },
//   { label: '作战活动', value: '14Zzhd' },
//   { label: '作战信息交互', value: '15Zzxxjh' },
//   { label: '体系能力框架', value: '21Txnlkj' },
//   { label: '作战活动-能力关系', value: '22Zzhdnl' },
//   { label: '体系能力需求', value: '23Txnlxq' },
// ]);

const rules = reactive<FormRules>({
  owner: [
    {
      required: true,
      validator: (rule, value: OptionItem, cb) => {
        console.log("value", value);
        if (!value.value) {
          return cb(new Error(locale.t("请选择所有者元素")));
        } else {
          cb();
        }
      }
    }
  ]
});

const saveLoading = ref(false);
const ruleFormRef = ref<FormInstance>();
let projectId = "";
const route = useRoute();
const token = archUtil.getCasic3Token();
const solutionCode = archUtil.getCasic3SolutionCode();
const fileList = ref<FileOption[]>([]);
// const selectedFile = ref<FileOption | null>(null);
let type: 1 | 2 = 1;
const filePaths = ref<string[]>([]);
let uuid = "";
const msg = ref("");
const barWidthPrecent = ref(0);
let loadingInstance: any = null;

watch(
  () => route.fullPath,
  () => {
    const routeQuery = route.query as unknown;
    const query = routeQuery as Params;
    type = parseInt(query.type as unknown as string) as 1 | 2;
    projectId = query.projectId;
    uuid = query.uuid;
    if (!solutionCode) {
      rules.importPath = { required: true, trigger: "blur", message: "请选择文件路径" };
    }
    // if (type == 1) {
    //   interfaceTypes.value = interfaceTypes.value.slice(0, 5);
    // } else {
    //   interfaceTypes.value = interfaceTypes.value.slice(5, interfaceTypes.value.length);
    // }
    // interfaceTypes.value.forEach(item => {
    //   rules[item.value] = { required: true, trigger: 'blur', message: '请选择文件路径' };
    // });
  },
  { immediate: true }
);

ipcRenderer.on(IpcMsg.WindowAbort, async () => loadingInstance?.removeImmediately());

onBeforeMount(() => {
  getFileList();
});

const getFileList = async () => {
  if (!token || !solutionCode) return;
  let appCode = "";
  const appCode1Str = "casic3.upload.appCode1";
  const appCode2Str = "casic3.upload.appCode2";
  if (type === 1) {
    appCode = archUtil.getCasic3Arg(appCode1Str);
  } else {
    appCode = archUtil.getCasic3Arg(appCode2Str);
  }
  fileList.value = await archService
    .FHJSGetFileList(appCode)
    .then((res: FileOption[]) => res.filter(item => /^[0-9]+(?![0-9.]).*\.json$/.test(item.name)));
  filePaths.value = fileList.value.map(item => item.fileUrl);
};

// const selectFile = (file: FileOption) => {
//   selectedFile.value = file;
//   form.importPath = file.fileUrl;
// };

const selectOwner = async () => {
  const result = await modelTreeSelectWindow.popup({
    loadMethod: "getPropertyTreeList",
    loadParams: JSON.stringify({
      row: {
        modelId: "",
        key: "",
        dataType: PropertyDataType.INSTANCE,
        moreBtnCondition: MetaclassType.Package,
        isMultiplicity: false,
        checkMethod: "",
        updateMethod: ""
      },
      projectId
    }),
    selectedId: form.owner.value,
    attrTip: "radio",
    title: "选择元素",
    delay: false,
    showNodeLabel: true,
    nullable: false,
    disableReadonlyNode: true
  });
  if (result.success) {
    const selectedId = result.selectedId as string;
    if (selectedId !== form.owner.value) {
      const typeModel = await modelService.getModelData(projectId, selectedId);
      form.owner = {
        value: typeModel.id,
        label: typeModel.name,
        icon: typeModel.icon
      };
    }
  }
};

const changePath = (type1: "dir" | "zip") => {
  if (type1 === "dir") {
    localFile
      .chooseDir({
        title: "选择文件夹",
        defaultPath: form.importPath
      })
      .then(res => {
        if (res.filePaths[0]) {
          form.importPath = res.filePaths[0];
        }
      });
  } else {
    localFile
      .chooseFile({
        title: "选择压缩包",
        defaultPath: form.importPath,
        filters: [
          {
            name: "zip/rar",
            extensions: ["zip", "rar"]
          }
        ]
      })
      .then(({ files }) => {
        if (files[0]) {
          form.importPath = files[0].path;
        }
      });
  }
};

const handleSave = async () => {
  if (!ruleFormRef.value) return;
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;

  // saveLoading.value = true;
  msg.value = "正在导入，请稍后...";
  barWidthPrecent.value = 0;
  LoadingVue.popup({
    msg,
    barWidthPrecent,
    getPortal: (item: any) => {
      loadingInstance = item;
    }
  });

  // const formData = { ...form };
  // delete formData.owner;
  // const filePaths: {type: string, filePath: string}[] = [];
  // for (let key in formData) {
  //   filePaths.push({ type: key, filePath: formData[key] });
  // }
  ipcWindowUtil.sendWindowChange({ success: true, ownerId: form.owner.value, filePath: form.importPath, filePaths: [...filePaths.value] });
  getImportProcess();
};

const getImportProcess = async () => {
  let polling = true;
  let success = true;
  while (polling) {
    await sleep(1);
    const { precent, message } = await archService.getCasic3Process(projectId, uuid).catch(() => {
      success = false;
      return {
        precent: 100,
        message: "导入失败"
      };
    });
    message && (msg.value = message);
    precent && (barWidthPrecent.value = precent);

    if (precent === 100) {
      await sleep(0.5);
      polling = false;
      break;
    }
  }
  loadingInstance?.removeImmediately();
  if (success) {
    handleclose({ success: true });
  }
};

function handleclose(data: CloseData) {
  saveLoading.value = false;
  ipcWindowUtil.closeWindow(data);
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
body .el-select-dropdown .el-select-dropdown__list {
  max-height: 150px;
  .el-select-dropdown__item {
    justify-content: space-between;
    padding-right: 30px;
    &::after {
      right: 12px !important;
    }
    .glay-text {
      color: var(--el-text-color-secondary) !important;
      font-size: 13px !important;
    }
  }
}

.v-FHJS-import {
  flex: 1;
  display: flex;
  overflow: hidden;
  .FHJS-import-container {
    flex: 1;
    overflow: hidden;
    padding: 32px;
    .el-form-item {
      height: 32px;
      margin-bottom: 14px;
      .el-form-item__label {
        line-height: 32px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .el-input__wrapper {
        border: 1px solid rgba(0, 0, 0, 0.15);
        box-shadow: none;
        input {
          height: 24px;
        }
      }
      .el-select {
        width: 100%;
        .el-select__wrapper {
          border: 1px solid rgba(0, 0, 0, 0.15);
          box-shadow: none;
          border-radius: 0;
          height: 28px;
          .el-select__icon {
            transition: none;
            width: 20px;
          }
        }
      }
      .el-button {
        border-color: rgba(0, 0, 0, 0.15);
        padding: 8px;
        border-radius: 0;
        &:hover {
          border-color: var(--md-primary-color);
        }
      }
      .ownerBox {
        height: 28px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        position: relative;
        padding-left: 7px;
        padding-right: 34px;
        ._btn {
          position: absolute;
          display: inline-block;
          cursor: pointer;
          top: 50%;
          right: 7px;
          transform: translateY(-50%);
        }
      }
    }

    .el-row {
      width: 100%;
      .el-col {
        min-height: 32px;
        display: flex;
        align-items: center;
      }
    }
    .interface-path-box {
      position: relative;
      .el-input__wrapper {
        padding-right: 34px;
        box-shadow: none !important;
      }
      ._btn,
      .dropdown-box {
        position: absolute;
        display: inline-block;
        cursor: pointer;
        top: 50%;
        right: 14px;
        transform: translateY(-50%);
      }
      .el-input__suffix {
        position: absolute;
        top: 50%;
        right: 8px;
        transform: translateY(-50%);
      }
      .dropdown-file-box {
        width: 100%;
        border: 1px solid rgba(0, 0, 0, 0.15);
        height: 28px;
        .c-dropdown {
          width: 100%;
          height: 100%;
        }
        .dropdown-file-content-box {
          height: 100%;
          display: flex;
          align-items: center;
        }
      }
    }
    .gray-text {
      color: gray;
    }
  }
}
</style>
